// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  var {
    op,
    _openid,
    gold
  } = event

  var myInfo = await db.collection("User").where({
    _openid: wxContext.OPENID
  }).get()
  myInfo = myInfo.data[0]

  if (_openid) {
    var userInfo = await db.collection("User").where({
      _openid: _openid,
    }).get()
    userInfo = userInfo.data[0]
  }
    //增加活跃值
    await db.collection('User').where({
      _openid: wxContext.OPENID,
    }).update({
      data: {
        active: _.inc(1),
      }
    })
    
  switch (op) {
   
    case 'house':
      return house();
      break;
      case 'repair':
        return repair();
        break;
  }



  // 升级房子
  async function house() {
    if (myInfo.gold < 10000) {
      return 'goldNotEnough'
    }
    if (myInfo.house.roomSum > 3) {
      return 'roomEnough'
    }
    await db.collection('User').where({
      _openid: wxContext.OPENID
    }).update({
      data: {
        'gold': _.inc(-10000),
        'house.roomSum': _.inc(1)
      }
    })
    return {
      roomSum: myInfo.house.roomSum + 1
    }

  }
// 维修房子
async function repair() {
  if (myInfo.gold < 50) {
    return 'goldNotEnough'
  }
  if (myInfo.house.life > 95) {
    return 'lifeEnough'
  }
  await db.collection('User').where({
    _openid: wxContext.OPENID
  }).update({
    data: {
      'gold': _.inc(-50),
      'house.life': _.inc(5)
    }
  })
  return {
    roomSum:'repaired'
  }

}
  

}